package com.yz.interceptor;


import com.yz.core.exception.TokenException;
import com.yz.dto.UserToken;
import com.yz.security.UserTokenThreadLocal;
import com.yz.service.impl.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1.获取token
        String token = request.getHeader("token");

        // 获取请求方式
        String method = request.getMethod();
        if ("options".equalsIgnoreCase(method)) {
            return true; // 如果是大头兵直接放行，不要在校验token
        }

        // 2.校验token合法性
        if (ObjectUtils.isEmpty(token)) {
            throw new TokenException(101, "token为空");
        }

        // 校验token合法性
        UserToken userToken = tokenService.getToken(token);
        if (userToken == null) {
            throw new TokenException(101, "token有误");
        }

        // 把userToken保存到ThreadLocal中
        UserTokenThreadLocal.set(userToken);

        // 放行
        return true;
    }

    // controller执行之后调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // controller执行完了，可以把ThreadLocal删除了
        UserTokenThreadLocal.remove();
    }
}
